/**
 * @author spider
 * Implementation of socket for the dispacher (see Socket on core.message)
 */
package br.unb.core.dispatcher;

import br.unb.core.message.Message;
import br.unb.core.status.StatusSocket;
import br.unb.core.synchronism.Synchronism;
import br.unb.utils.Console;
import br.unb.utils.Resource;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 *
 * @author spider
 */
public class DispatcherSocket extends br.unb.core.message.Socket {

    private static final DispatcherSocket INSTANCE = new DispatcherSocket();//no lazy initialization

    public static DispatcherSocket getInstance() {
        return INSTANCE;
    }

    private DispatcherSocket() {
        try {
            super.setName("8888");
            socket = new DatagramSocket(DISPATCHER_PORT);
        } catch (SocketException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @Override
    public Message receive() {
        Message recMessage = null;
        try {
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            this.socket.receive(packet);
            lastInPacket = packet;
            recMessage = new Message(buffer);
            printError(
                    Resource.getString("Receive:")//14 chars wide
                    + packet.getAddress().getHostAddress() 
                    + ":" + packet.getPort()
                    + ". ", recMessage);
            //Different code from super() is below
            if (recMessage.getType() == Message.Type.START_SYNCCLIENT) {
                Synchronism syncModel = (Synchronism) recMessage.getSyncModel();
                syncModel.setSyncManagerIp(packet.getAddress().getHostAddress());
            }
        } catch (SocketTimeoutException ex) {
            Console.showMessageDialog(
                    Resource.getString("SOCKET_TIMEOUT") + ex.getMessage());
        } catch (IOException ioe) {
            Console.showMessageDialog(
                    Resource.getString("NETWORK_DISCONNECTED") + ioe.getMessage());
        }
        return recMessage;
    }

    public void sendDispacher(Message message, String dst) {
        try {
            send(message, InetAddress.getByName(dst), DISPATCHER_PORT);
        } catch (UnknownHostException ex) {
        }
    }

    public void sendDispacher(Message message, InetAddress dst) {
        send(message, dst, DISPATCHER_PORT);
    }

    public void sendStatus(Message message) {
        send(message, lastInPacket.getAddress(), StatusSocket.STATUS_PORT);
    }


    public void answer(Message message) {
        super.answer(message);
    }
}
